#include <QDoubleSpinBox>
#include "double-spin-box-delegate.h"
#include <float.h>

DoubleSpinBoxDelegate::DoubleSpinBoxDelegate (QObject *parent) :
    QStyledItemDelegate(parent), m_oldValue(0), m_rangeStart(0), m_rangeEnd(1000000), m_defaultValue(0)
{
}

QWidget* DoubleSpinBoxDelegate::createEditor (QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
    Q_UNUSED(option);
    Q_UNUSED(index);
    QDoubleSpinBox* spinBox = new QDoubleSpinBox(parent);
    spinBox->setRange(m_rangeStart, m_rangeEnd);
    spinBox->setValue(m_defaultValue);
    return spinBox;
}

void DoubleSpinBoxDelegate::setEditorData (QWidget* editor, const QModelIndex& index) const
{
    double value = index.data(Qt::UserRole).toDouble();
    m_oldValue = value;

    QDoubleSpinBox* spinBox = static_cast<QDoubleSpinBox*>(editor);
    spinBox->setValue(value);
}

void DoubleSpinBoxDelegate::setModelData (QWidget* editor, QAbstractItemModel* model, const QModelIndex& index) const
{
    QDoubleSpinBox* spinBox = static_cast<QDoubleSpinBox*>(editor);

    double newValue = spinBox->value();
    if (newValue == m_oldValue)
        return;

    model->setData(index, newValue, Qt::UserRole);
}

void DoubleSpinBoxDelegate::setRange(double rangeStart, double rangeEnd)
{
    m_rangeStart = rangeStart;
    m_rangeEnd = rangeEnd;
}

void DoubleSpinBoxDelegate::setDefaultValue(double defaultValue)
{
    m_defaultValue = defaultValue;
}
